import type { RouteLocationNormalized, NavigationGuardNext } from "vue-router";
import {
  routerRef,
  useUserStoreHook,
  usePermissionStoreHook,
} from "jmash-core";

import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false }); // 进度条

const permissionStore = usePermissionStoreHook();

// 白名单路由
const whiteList = ["/login", "/secondLogin"];

routerRef.value.beforeEach(
  async (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    NProgress.start();
    const hasToken = localStorage.getItem("accessToken");
    const userStore = useUserStoreHook();
    const tenant = userStore.user.tenant;
    if (hasToken) {
      if (to.path === "/login") {
        // 如果已登录，跳转首页
        next({ path: "/", query: Object.assign(to.query, { tenant: tenant }) });
        NProgress.done();
      } else {
        const hasRoles =
          userStore.user.roleCodes && userStore.user.roleCodes.length > 0;
        if (hasRoles) {
          // 未匹配到任何路由，跳转404
          if (to.matched.length === 0) {
            if (from.name){
              next({ name: from.name, query: { tenant: tenant } })
            }else{
              next({ path: "/404", query: { tenant: tenant } });
            }
          } else if (to.query.tenant) {
            next();
          } else {
            to.query.tenant = tenant;
            next({
              ...to,
            });
          }
        } else {
          try {
            const rolesPerms = await userStore.getRoleInfo();
            await userStore.getUserInfo();
            const accessRoutes =
              await permissionStore.generateRoutes(rolesPerms);
            accessRoutes.forEach((route: any) => {
              routerRef.value.addRoute(route);
            });
            next({
              ...to,
              replace: true,
              query: Object.assign(to.query, { tenant: tenant }),
            });
          } catch (error) {
            // 移除 token 并跳转登录页
            await userStore.resetToken();
            next({
              path: `/login?redirect=${to.path}`,
              query: { tenant: tenant },
            });
            NProgress.done();
          }
        }
      }
    } else {
      // 未登录可以访问白名单页面
      if (whiteList.indexOf(to.path) !== -1 && to.query.tenant) {
        next();
      } else if (whiteList.indexOf(to.path) !== -1) {
        to.query.tenant = tenant;
        next({
          ...to,
          replace: true,
        });
      } else {
        next({ path: `/login?redirect=${to.path}`, query: { tenant: tenant } });
        NProgress.done();
      }
    }
  }
);

routerRef.value.afterEach(() => {
  NProgress.done();
});
